package com.application.model.elegircolegio.retrieve;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;

import com.application.model.RetrivierWeb;
import com.application.model.elegircolegio.ManagerElegirColegioEntity;
import com.application.model.elegircolegio.entries.ElegirColegioElement;
import com.application.model.elegircolegio.entries.ElegirColegioEntity;

public class ManagerBusqueda extends RetrivierWeb{

	private ManagerDetalle			managerDetalle;
	private ManagerElegirColegioEntity 	informacion;
	
	public ManagerBusqueda(ManagerElegirColegioEntity informacion) {
		this.informacion = informacion;
		managerDetalle = new ManagerDetalle(informacion);
	}
	

	@Override
	public void processContent(String data, String parentName) {
//		if(parentName.equals("busqueda")){
        processContentBusqueda(data,parentName);
//        }else if(parentName.equals("detalle")){
////        	managerDetalle.processContentDetalle(data,parentName);
//        }
	}
	public void processContentBusqueda(String data, String parentName) {
    	Pattern     pattern = null;
        Matcher     matcher = null;
        String      regex = null;
    	//infoWindowAnchor = new GPoint(.*?)GUnload()
//        data = unescapeHtml(data);
        //data = StringEscapeUtils.escapeSql(data);
    	regex = "<div class=price(.*?)\\.corners";
        pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL|Pattern.UNICODE_CASE|Pattern.UNIX_LINES);
        matcher = pattern.matcher(data);
        
        while (matcher.find()) {
        	procesarAvisos(matcher.group(1),parentName);
        }
        regex = "infoWindowAnchor = new GPoint(.*?)GUnload";
        pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL|Pattern.UNICODE_CASE|Pattern.UNIX_LINES);
        matcher = pattern.matcher(data);
        
        while (matcher.find()) {
        	processUbicacionMap(matcher.group(1));
        	//procesarAvisos(matcher.group(1));
        }
    }
	
	private void procesarAvisos(String data, String zonaKey) {
    	Pattern     pattern = null;
        Matcher     matcher = null;
        String      regex = null;
        String      nameColegio = "";
        
        String      urlDetalle = "";
        String      servicioEducativo = "";
        
        regex = ">(.*?)</div>(.*?)<a href=\"(.*?)\"(.*?)Ver ficha del Colegio<h3><strong>(.*?)</strong>(.*?)<div>(.*?)<br>(.*?)\\.</div>(.*?)<div style=\"margin-top: 10px\">(.*?)<script>\\$\\(document\\)\\.ready\\( function\\(\\)\\{\\$\\('\\.rounded";
        pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL|Pattern.UNICODE_CASE|Pattern.UNIX_LINES);
        matcher = pattern.matcher(data);
        
        while (matcher.find()) {
            nameColegio = matcher.group(5);
            
            urlDetalle = matcher.group(3);            
            servicioEducativo = matcher.group(8);
            
            
            //logger.info("INSERT INTO institucion(name) VALUES('"+escapeSql(nameColegio)+"');");
            
            
            generarUbicacion(matcher.group(7),servicioEducativo,urlDetalle,matcher.group(4),nameColegio,zonaKey,matcher.group(10));
            
        }
		
	}
	private void generarServicioEducativo(String data,String pais,String provincia,String partido,String nameColegio,String zonaKey) {
        Pattern     pattern = null;
        Matcher     matcher = null;
        String      regex = null;
        String      tipo = "";
        String      ideologia = "";
        String		updateStr = "";
        if(!data.isEmpty()){
            regex = "(.*?),(.*?),(.*)";
            pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL|Pattern.UNICODE_CASE|Pattern.UNIX_LINES);
            matcher = pattern.matcher(data);

            while (matcher.find()) {
                tipo = generateTipo(matcher.group(1));
                
                ideologia = generarIdeologia(matcher.group(3));
                
                updateStr = "UPDATE institucion "
                        + " SET "                        
                        + " tipo_id= (SELECT id FROM tipo where UPPER(name)=UPPER('"+tipo+"'))";
                if(!ideologia.isEmpty()){
                	updateStr +=  ", ideologia_id= (SELECT id FROM ideologia where UPPER(name)=UPPER('"+ideologia+"'))";
                }
                updateStr +=  " WHERE "+getWhereColegioUpdate(pais, provincia, partido, nameColegio,zonaKey)+";";
                
                logger.info(updateStr);
                informacion.updateTipoEIdelogia(nameColegio,tipo,ideologia);
                processJornada(matcher.group(2),pais,provincia,partido,nameColegio,zonaKey);
            }
        }
    }
	
	private void generarUbicacion(String data,String servicioEducativo,String urlDetalle,String dataImage,String nameColegio, String zonaKey,String niveles) {
        Pattern     pattern = null;
        Matcher     matcher = null;
        String      regex = null;
        String      direccion = "";
        String      pais = "";
        String      provincia = "";
        String      partido = "";        
        
        if(!data.isEmpty()){
            regex = "(.*?),(.*?),(.*?),(.*?)\\.";
            pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL|Pattern.UNICODE_CASE|Pattern.UNIX_LINES);
            matcher = pattern.matcher(data);

            while (matcher.find()) {
                direccion = matcher.group(1).trim();
                pais = matcher.group(4).trim();
                provincia = matcher.group(3).trim();
                partido = getPartidoName(matcher.group(2));
                if(zonaKey.equals("Capital Federal")){
                	logger.info("INSERT INTO institucion(name,direccion,pais_id,provincia_id,partido_id,localidad_id) " +
                    		" VALUES('"+escapeSql(nameColegio)+"',"+
                    		" '"+direccion+"'," +
                    		" (SELECT id FROM pais where UPPER(name)=UPPER('"+pais+"'))," +
                    		" (SELECT id FROM provincia where UPPER(name)=UPPER('"+zonaKey+"'))," +
                    		" (SELECT id FROM partido where UPPER(name)=UPPER('"+zonaKey+"'))," +
                    		" (SELECT id FROM localidad where "+getWherePartidoName(partido)+" AND " +
                    			" partido_id = (SELECT id FROM partido where UPPER(name)=UPPER('"+zonaKey+"')) )"+
                    				");");
                }else{
                logger.info("INSERT INTO institucion(name,direccion,pais_id,provincia_id,partido_id) " +
                		" VALUES('"+escapeSql(nameColegio)+"',"+
                		" '"+direccion+"'," +
                		" (SELECT id FROM pais where UPPER(name)=UPPER('"+pais+"'))," +
                		" (SELECT provincia_id FROM partido where UPPER(name)=UPPER('"+partido+"'))," +
                		" (SELECT id FROM partido where UPPER(name)=UPPER('"+partido+"')));");
                }
                
//                logger.info("INSERT INTO institucion "
//                        + " SET direccion='"+direccion+"',"
//                        + " pais_id= (SELECT id FROM pais where UPPER(name)=UPPER('"+pais+"')),"
//                        + " provincia_id= (SELECT id FROM provincia where UPPER(name)=UPPER('"+provincia+"')),"
//                        + " partido_id= (SELECT id FROM partido where UPPER(name)=UPPER('"+partido+"'))"
//                        + " WHERE name='"+escapeSql(nameColegio)+"';");
                //, pais_id="++" WHERE name ='"+nameColegio+"'");
            }
            informacion.agregarNuevaInformacion(nameColegio,pais,provincia,partido,direccion,zonaKey);
            generarServicioEducativo(servicioEducativo,pais,provincia,partido,nameColegio,zonaKey);            
            processNiveles(niveles,pais,provincia,partido,nameColegio,zonaKey);
            leerContentDetalle(urlDetalle,pais,provincia,partido,nameColegio,zonaKey);
            generateImageFile(dataImage,pais,provincia,partido,nameColegio,zonaKey);
        }
        
    }
    
    


	private String getPartidoName(String data) {
		String name = "";
		name = data.replaceAll("- CABA", "");
		name = name.trim();
		return name;
	}


	private void processJornada(String data,String pais,String provincia,String partido,String colegioNombre,String zonaKey) {
        String      valor = "";
        

        String[] datoVector = data.split("&");
        if(datoVector!=null){
            for (String item : datoVector) {
                valor = item.replace("de Jornada", "");
                valor = valor.replace("CompletaJornada", "");
                
                valor = valor.replace(" ", "");
                if(valor.endsWith("CompletaJornadaSimple")){
                	System.out.println("");
                }
                if(!valor.endsWith("de")){
                	logger.info("INSERT INTO jornada_institucion(jornada_id,institucion_id) "
                        + "VALUES("                        
                        + " (SELECT id from jornada WHERE UPPER(name)=UPPER('"+escapeSql(valor)+"')),"
                        + " (SELECT id from institucion WHERE "+getWhereColegioUpdate(pais, provincia, partido, colegioNombre,zonaKey)+")"
                        + ");");
                	informacion.addJornada(colegioNombre,valor);
                }
                
            }
        }
    }
    private void processUbicacionMap(String data) {
        Pattern     pattern = null;
        Matcher     matcher = null;
        String      regex = null;
        String      nameColegio = "";
        String      latitud = "";
        String      longitud = "";

        regex = "GMarker\\(new GLatLng\\((.*?),(.*?)\\),(.*?)openInfoWindowHtml\\('(.*?)'\\)(.*?)";
        pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL|Pattern.UNICODE_CASE|Pattern.UNIX_LINES);
        matcher = pattern.matcher(data);
        
        while (matcher.find()) {
            latitud = matcher.group(1);
            longitud = matcher.group(2);
            nameColegio = matcher.group(4);
            logger.info("UPDATE institucion SET latitud="+latitud+", longitud="+longitud+" WHERE name ='"+escapeSql(nameColegio)+"';");
            informacion.setLocation(nameColegio,longitud,latitud);
        }
    }
    private void leerContentDetalle(String urlDetalle,String pais,String provincia,String partido,String nombreColegio,String zonaKey) {
        managerDetalle.retrivie(urlDetalle, "<!-- titular -->", "<form",pais,provincia,partido,nombreColegio,zonaKey);
    }


    /**
     * Asocia a un colegio con los distintos niveles definidos
     * @param data
     * @param nameColegio 
     */
    private void processNiveles(String data,String pais,String provincia,String partido, String nameColegio,String zonaKey) {
        Pattern     pattern = null;
        Matcher     matcher = null;
        String      regex = null;
        
        String      nivel = "";

        
        regex = "class=\"rounded\">(.*?)</div>";
        pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL|Pattern.UNICODE_CASE|Pattern.UNIX_LINES);
        matcher = pattern.matcher(data);
        
        while (matcher.find()) {
            nivel = matcher.group(1);
            nivel = nivel.trim();
            if(nivel.equals("Escuela Especial")){
            	nivel = "Especial";	
            }
            logger.info("INSERT INTO nivel_institucion(nivel_id,institucion_id) "
                    + " VALUES("
                    + " (SELECT id FROM nivel WHERE UPPER(name)=UPPER('"+nivel+"')),"
                    + " (SELECT id FROM institucion WHERE "+getWhereColegioUpdate(pais, provincia, partido, nameColegio,zonaKey)+")"
                    + ");");
            informacion.addNivel(nameColegio,nivel);
        }
    }
    private String generateImageFile(String data,String pais,String provincia,String partido,String nombreColegio,String zonaKey) {
        Pattern     pattern = null;
        Matcher     matcher = null;
        String      regex = null;
        String      path = "";
        String      url = "";
        String      urlImagenBEDB = "";
        String		nombreArchivo = "";
        if(!data.isEmpty()){
            urlImagenBEDB = "/images/uploads/instituciones/logos";
            regex = "/phpthumb/phpThumb.php\\?src=(.*?)&h=87";
            pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL|Pattern.UNICODE_CASE|Pattern.UNIX_LINES);
            matcher = pattern.matcher(data);

            while (matcher.find()) {
                url = matcher.group(1);
                nombreArchivo = guardarImagenEnDisco(url,urlImagenBEDB);
                if(!nombreArchivo.isEmpty()){
                	logger.info("UPDATE institucion "
                        + " SET "
                        + " urlFotoLogo='"+urlImagenBEDB+nombreArchivo+"'"
                        + " WHERE "+getWhereColegioUpdate(pais, provincia, partido, nombreColegio,zonaKey)+";");
                	informacion.setUrlImagenLogo(nombreColegio,urlImagenBEDB+nombreArchivo);
                }
            }
        }
        return path;
    }

    private String guardarImagenEnDisco(String urlWeb,String urlImagenBEDB) {
        BufferedImage   image = null;
        String          urlImagenBE = "";
        String          extension = "";
        String          nombreArchivo = "";
        String          nombreArchivoOut = "";
        urlImagenBE = "/home/jhonny/NetBeansProjects/BCWeb/web"+urlImagenBEDB;
//        urlImagenBE = "/home/jhonny/borrar";
        try {
 
            URL url = new URL(urlWeb);
            image = ImageIO.read(url);
            
            int dotPos = urlWeb.lastIndexOf(".");
            extension = urlWeb.substring(dotPos);
            extension = extension.replace(".", "");
            dotPos = urlWeb.lastIndexOf("/");
            nombreArchivo = urlWeb.substring(dotPos);
            ImageIO.write(image, extension,new File(urlImagenBE+nombreArchivo)); 
            nombreArchivoOut = nombreArchivo;
        } catch (Exception e) {
            //logger.error(e,e.fillInStackTrace());
        }finally{
            
        }
        return nombreArchivoOut;
    }
//    public  void saveImage(String imageUrl, String destinationFile) throws IOException {
//		URL url = new URL(imageUrl);
//		InputStream is = url.openStream();
//		OutputStream os = new FileOutputStream(destinationFile);
//
//		byte[] b = new byte[2048];
//		int length;
//
//		while ((length = is.read(b)) != -1) {
//			os.write(b, 0, length);
//		}
//
//		is.close();
//		os.close();
//	}
    private String generateTipo(String dato) {
        String value = "";
        value = dato.replace("Colegio ", "");
        value = value.replace("Institucion ", "");
        value = value.replace("Institución ", "");        
        return value;
    }

    private String generarIdeologia(String dato) {
         String value = "";
        value = dato.replace("con orientación", "");
        value = value.replace(" ", "");
        return value;
    }
	
	@Override
	public void retrieve() {		
	}
	
}
